package com.raylu.gmallbigscreen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.raylu.gmallbigscreen.beans.ProductStats;
import com.raylu.gmallbigscreen.mapper.ProductStatsMapper;
import com.raylu.gmallbigscreen.service.ProductStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:
 * <p>
 * Create by lucienoz on 2022/1/10.
 * Copyright © 2022 lucienoz. All rights reserved.
 */
@Service
public class ProductStatsServiceImpl implements ProductStatsService {
    @Autowired
    private ProductStatsMapper productStatsMapper;
    @Override
    public BigDecimal getGmv(Integer date) {
        if (date==0) {
            date = getNow();
        }
        return productStatsMapper.selectGmv(date);
    }

    @Override
    public JSONObject getProductStatsByTm(Integer date, Integer limit) {
        if (date==0) {
            date = getNow();
        }
        List<ProductStats> productStats = productStatsMapper.selectProductStatsByTm(date, limit);
        List<String> tmList = productStats.stream().map(r-> r.getTm_name()).collect(Collectors.toList());
        List<BigDecimal> orderAmountList = productStats.stream().map(r -> r.getOrder_amount()).collect(Collectors.toList());
        List<Long> orderCountList = productStats.stream().map(r -> r.getOrder_cnt()).collect(Collectors.toList());
        String jsonStr = "{\"status\":0,\"msg\":\"\",\"data\":{\"categories\":[\"电子网络\",\"销售\",\"教育\",\"建筑\",\"娱乐传媒\"],\"series\":[{\"name\":\"男\",\"unit\":\"%\",\"data\":[76,65,50,48,42]},{\"name\":\"女\",\"unit\":\"%\",\"data\":[24,35,50,52,58]}],\"yUnit\":\"%\"}}";
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject data = jsonObject.getJSONObject("data");
        data.put("categories", tmList);
        JSONArray series = data.getJSONArray("series");
        JSONObject serie0 = series.getJSONObject(0);
        serie0.put("name", "订单数");
        serie0.put("unit", "个");
        serie0.put("data", orderCountList);
        JSONObject serie1 = series.getJSONObject(1);
        serie1.put("name", "订单总金额");
        serie1.put("unit", "万¥");
        serie1.put("data", orderAmountList);

        data.put("yUnit", "");

        return jsonObject;
    }

    private Integer getNow(){
        DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = LocalDateTime.now().format(yyyyMMdd);
        int i = Integer.parseInt(format);
        return i;
    }
}
